/**
 * 卡片管理相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 获取卡片列表
 * @param {object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 * @param {string} params.keyword - 搜索关键词
 * @param {number} params.type - 卡片类型
 * @param {number} params.status - 卡片状态
 * @returns {Promise} 卡片列表
 */
export const getCardList = (params = {}) => {
  return request.get('/card/list', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '', type, status } = queryParams
    
    // 模拟卡片数据
    const mockCards = Array.from({ length: 100 }, (_, index) => ({
      id: index + 1,
      cardNo: `CARD${String(index + 1).padStart(8, '0')}`,
      cardName: `测试卡片${index + 1}`,
      type: Math.floor(Math.random() * 4) + 1, // 1-4
      typeName: ['普通卡', 'VIP卡', '钻石卡', '黑金卡'][Math.floor(Math.random() * 4)],
      status: Math.random() > 0.2 ? 1 : Math.floor(Math.random() * 4) + 1, // 1-4
      statusName: ['正常', '冻结', '注销', '挂失'][Math.floor(Math.random() * 4)],
      balance: Math.floor(Math.random() * 10000) / 100,
      points: Math.floor(Math.random() * 1000),
      holderName: `持卡人${index + 1}`,
      holderPhone: `138${String(index + 1).padStart(8, '0')}`,
      issueDate: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      expireDate: new Date(Date.now() + Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString()
    }))
    
    // 过滤数据
    let filteredCards = mockCards
    if (keyword) {
      filteredCards = mockCards.filter(card => 
        card.cardNo.includes(keyword) || 
        card.cardName.includes(keyword) ||
        card.holderName.includes(keyword) ||
        card.holderPhone.includes(keyword)
      )
    }
    if (type) {
      filteredCards = filteredCards.filter(card => card.type === Number(type))
    }
    if (status) {
      filteredCards = filteredCards.filter(card => card.status === Number(status))
    }
    
    // 分页
    const total = filteredCards.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredCards.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取卡片详情
 * @param {number} id - 卡片ID
 * @returns {Promise} 卡片详情
 */
export const getCardDetail = (id) => {
  return request.get(`/card/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      cardNo: `CARD${String(id).padStart(8, '0')}`,
      cardName: `测试卡片${id}`,
      type: 1,
      typeName: '普通卡',
      status: 1,
      statusName: '正常',
      balance: 1234.56,
      points: 500,
      holderName: `持卡人${id}`,
      holderPhone: `138${String(id).padStart(8, '0')}`,
      holderIdCard: `110101199001010${String(id).padStart(3, '0')}`,
      holderAddress: '北京市朝阳区测试街道123号',
      issueDate: '2024-01-01T00:00:00.000Z',
      expireDate: '2025-12-31T23:59:59.999Z',
      description: '这是一张测试卡片',
      createTime: '2024-01-01T00:00:00.000Z',
      updateTime: new Date().toISOString(),
      // 交易记录
      transactions: Array.from({ length: 10 }, (_, index) => ({
        id: index + 1,
        type: Math.random() > 0.5 ? 'income' : 'expense',
        amount: Math.floor(Math.random() * 1000) / 100,
        description: `交易记录${index + 1}`,
        createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
      }))
    })
  })
}

/**
 * 创建卡片
 * @param {object} data - 卡片数据
 * @returns {Promise} 创建结果
 */
export const createCard = (data) => {
  return request.post('/card', data, {}, (params) => {
    const { cardName, type, holderName, holderPhone } = params
    
    if (!cardName || !type || !holderName || !holderPhone) {
      return mockError('请填写完整的卡片信息', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      cardNo: `CARD${String(Date.now()).slice(-8)}`,
      ...params,
      status: 1,
      balance: 0,
      points: 0,
      issueDate: new Date().toISOString(),
      expireDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
      createTime: new Date().toISOString()
    }, '卡片创建成功')
  })
}

/**
 * 更新卡片
 * @param {number} id - 卡片ID
 * @param {object} data - 卡片数据
 * @returns {Promise} 更新结果
 */
export const updateCard = (id, data) => {
  return request.put(`/card/${id}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(id),
      ...params,
      updateTime: new Date().toISOString()
    }, '卡片更新成功')
  })
}

/**
 * 删除卡片
 * @param {number} id - 卡片ID
 * @returns {Promise} 删除结果
 */
export const deleteCard = (id) => {
  return request.delete(`/card/${id}`, {}, () => {
    return mockSuccess(null, '卡片删除成功')
  })
}

/**
 * 制卡申请
 * @param {object} data - 申请数据
 * @returns {Promise} 申请结果
 */
export const applyCard = (data) => {
  return request.post('/card/apply', data, {}, (params) => {
    const { type, holderName, holderPhone, holderIdCard } = params
    
    if (!type || !holderName || !holderPhone || !holderIdCard) {
      return mockError('请填写完整的申请信息', 400)
    }
    
    return mockSuccess({
      applicationId: Date.now(),
      status: 'pending',
      ...params,
      applyTime: new Date().toISOString()
    }, '制卡申请提交成功')
  })
}

/**
 * 领卡确认
 * @param {number} id - 卡片ID
 * @param {object} data - 确认数据
 * @returns {Promise} 确认结果
 */
export const receiveCard = (id, data) => {
  return request.post(`/card/${id}/receive`, data, {}, () => {
    return mockSuccess({
      cardId: Number(id),
      receiveTime: new Date().toISOString(),
      status: 'received'
    }, '领卡确认成功')
  })
}

/**
 * 卡片充值
 * @param {number} id - 卡片ID
 * @param {object} data - 充值数据
 * @param {number} data.amount - 充值金额
 * @returns {Promise} 充值结果
 */
export const rechargeCard = (id, data) => {
  return request.post(`/card/${id}/recharge`, data, {}, (params) => {
    const { amount } = params
    
    if (!amount || amount <= 0) {
      return mockError('充值金额必须大于0', 400)
    }
    
    return mockSuccess({
      cardId: Number(id),
      amount: Number(amount),
      transactionId: Date.now(),
      rechargeTime: new Date().toISOString()
    }, '充值成功')
  })
}

/**
 * 卡片消费
 * @param {number} id - 卡片ID
 * @param {object} data - 消费数据
 * @param {number} data.amount - 消费金额
 * @param {string} data.description - 消费描述
 * @returns {Promise} 消费结果
 */
export const consumeCard = (id, data) => {
  return request.post(`/card/${id}/consume`, data, {}, (params) => {
    const { amount, description } = params
    
    if (!amount || amount <= 0) {
      return mockError('消费金额必须大于0', 400)
    }
    
    return mockSuccess({
      cardId: Number(id),
      amount: Number(amount),
      description,
      transactionId: Date.now(),
      consumeTime: new Date().toISOString()
    }, '消费成功')
  })
}

/**
 * 冻结卡片
 * @param {number} id - 卡片ID
 * @param {object} data - 冻结原因
 * @returns {Promise} 冻结结果
 */
export const freezeCard = (id, data) => {
  return request.put(`/card/${id}/freeze`, data, {}, () => {
    return mockSuccess({
      cardId: Number(id),
      status: 'frozen',
      freezeTime: new Date().toISOString()
    }, '卡片冻结成功')
  })
}

/**
 * 解冻卡片
 * @param {number} id - 卡片ID
 * @returns {Promise} 解冻结果
 */
export const unfreezeCard = (id) => {
  return request.put(`/card/${id}/unfreeze`, {}, {}, () => {
    return mockSuccess({
      cardId: Number(id),
      status: 'normal',
      unfreezeTime: new Date().toISOString()
    }, '卡片解冻成功')
  })
}

/**
 * 挂失卡片
 * @param {number} id - 卡片ID
 * @param {object} data - 挂失原因
 * @returns {Promise} 挂失结果
 */
export const reportLostCard = (id, data) => {
  return request.put(`/card/${id}/lost`, data, {}, () => {
    return mockSuccess({
      cardId: Number(id),
      status: 'lost',
      lostTime: new Date().toISOString()
    }, '卡片挂失成功')
  })
}

/**
 * 注销卡片
 * @param {number} id - 卡片ID
 * @param {object} data - 注销原因
 * @returns {Promise} 注销结果
 */
export const cancelCard = (id, data) => {
  return request.put(`/card/${id}/cancel`, data, {}, () => {
    return mockSuccess({
      cardId: Number(id),
      status: 'cancelled',
      cancelTime: new Date().toISOString()
    }, '卡片注销成功')
  })
}

/**
 * 获取卡片交易记录
 * @param {number} id - 卡片ID
 * @param {object} params - 查询参数
 * @returns {Promise} 交易记录
 */
export const getCardTransactions = (id, params = {}) => {
  return request.get(`/card/${id}/transactions`, params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, type, startDate, endDate } = queryParams
    
    // 模拟交易记录
    const mockTransactions = Array.from({ length: 50 }, (_, index) => ({
      id: index + 1,
      cardId: Number(id),
      type: Math.random() > 0.5 ? 'income' : 'expense',
      amount: Math.floor(Math.random() * 1000) / 100,
      balance: Math.floor(Math.random() * 10000) / 100,
      description: `交易记录${index + 1}`,
      merchantName: `商户${index + 1}`,
      transactionNo: `TXN${String(Date.now() + index).slice(-10)}`,
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
    }))
    
    // 过滤数据
    let filteredTransactions = mockTransactions
    if (type) {
      filteredTransactions = filteredTransactions.filter(transaction => transaction.type === type)
    }
    if (startDate) {
      filteredTransactions = filteredTransactions.filter(transaction => 
        new Date(transaction.createTime) >= new Date(startDate)
      )
    }
    if (endDate) {
      filteredTransactions = filteredTransactions.filter(transaction => 
        new Date(transaction.createTime) <= new Date(endDate)
      )
    }
    
    // 分页
    const total = filteredTransactions.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredTransactions.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取卡片价格信息
 * @returns {Promise} 价格信息
 */
export const getCardPrices = () => {
  return request.get('/card/prices', {}, {}, () => {
    return mockSuccess([
      {
        type: 1,
        typeName: '普通卡',
        price: 10.00,
        description: '基础功能卡片',
        features: ['基础消费', '余额查询', '交易记录']
      },
      {
        type: 2,
        typeName: 'VIP卡',
        price: 50.00,
        description: 'VIP专享卡片',
        features: ['基础功能', '积分奖励', '优惠折扣', '专属客服']
      },
      {
        type: 3,
        typeName: '钻石卡',
        price: 200.00,
        description: '钻石级别卡片',
        features: ['VIP功能', '高额积分', '专属优惠', '绿色通道']
      },
      {
        type: 4,
        typeName: '黑金卡',
        price: 500.00,
        description: '顶级尊享卡片',
        features: ['钻石功能', '无限积分', '专属服务', '全球通用']
      }
    ])
  })
}